// var fs = require('fs.extra');
var path = require('path');
var fs = require('fs');
var root = path.join(__dirname, "src");
var dist = path.join(__dirname , "..", 'adf');
var jsdistFileName = path.join(dist, 'vueext.js');
var cssdistFileName = path.join(dist, 'vueext.css');
var jsdistFile = fs.createWriteStream(jsdistFileName);
var cssdistFile = fs.createWriteStream(cssdistFileName);


var log4js = require('log4js');
var ADF = require("adf-bundle-collector");

var logger = log4js.getLogger();
var bundlesRoot = path.join(__dirname, "src");
var adf = new ADF(bundlesRoot, logger);

var jsresourceFileList = [];
var cssresourceFileList = [];
module.exports = function(callback){
	adf.collect(function(error, bundleHolders){
		bundleHolders.forEach(function(element) {
			var resourceFiles = element.getAllResourceFiles();
			if(resourceFiles){
				resourceFiles.forEach(function(file) {
					jsresourceFileList.push(path.join(element.getName(), file));
				}, this);
			}
			var css_files = element.getCss();
			if(css_files){
				css_files.forEach(function(file) {
					cssresourceFileList.push(path.join(element.getName(), file));
				}, this);
			}
		}, this);
		function reduce(files, distFile,callback){
			function next(i){
				if(i >= files.length){
					return callback();
				} 
				var file = files[i];
				console.log('combine file: '+path.join(root, file));
				var src = fs.createReadStream(path.join(root, file));
				src.pipe(distFile, { end: false });
				src.on('end', next.bind(null, ++i));
			}
			next.bind(null,0)();
		};
		reduce(jsresourceFileList,jsdistFile, function(){
			reduce(cssresourceFileList,cssdistFile, function(){
				console.log('\x1b[32m%s\x1b[0m ', 'adf build completed.');
				if(callback){
					callback();
				}
			});
		});
	});
}

